package br.com.fiap.fiappizzas.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import br.com.fiap.fiappizzas.db.entities.Product;
import br.com.fiap.fiappizzas.db.entities.ProductType;

public class ProductDAO extends AbstractDAO<Product> {

	public ProductDAO(Context context) {
		super(context);
	}

	@Override
	public String getTableName() {
		return "tb_product";
	}

	@Override
	public String[] getColumns() {
		return new String[]{"id", "name", "description", "productType", "valor"};
	}

	@Override
	public Product buildEntity(Cursor cursor) {
		
		final Product p = new Product();
		
		p.setId(cursor.getLong(0));
		p.setName(cursor.getString(1));
		p.setDesc(cursor.getString(2));
		p.setType(ProductType.valueOf(cursor.getString(3)));
		p.setValue(cursor.getDouble(4));
		
		return p;
	}

	@Override
	public ContentValues buildContentValues(Product product) {
		
		final ContentValues values = new ContentValues();
        
		values.put("id", product.getId());  
        values.put("name", product.getName());
        values.put("description", product.getDesc());
        
        if (product.getType() != null) {
        	values.put("productType", product.getType().toString());
        }
        
        values.put("valor", product.getValue());
        
        return values;
        
	}
	
	public List<Product> findByType(ProductType type) {
		
		final SQLiteDatabase db = getReadableDB();
		
		Cursor cursor = 
	            db.query(getTableName(), 
	            getColumns(), 
	            " type = ?",  
	            new String[] { String.valueOf(type.toString()) }, 
	            null, 
	            null, 
	            null, 
	            null); 
	 
	    if (cursor != null) cursor.moveToFirst();
	 
	    final List<Product> entities = new ArrayList<Product>(cursor.getCount());
		
		while (cursor.moveToNext()) {
			entities.add(buildEntity(cursor));
		}
		
	    Log.d("getProductsByType("+type+")", null);
	 
	    return entities;
		
	}

}
